import 'package:bot_toast/bot_toast.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:shopping_group/base/base_constant.dart';
import 'package:shopping_group/common/common.dart';
import 'package:shopping_group/entity/count_entity.dart';
import 'package:shopping_group/entity/selectiont_entity.dart';
import 'package:shopping_group/entity/widget_entity.dart';
import 'package:shopping_group/modle/login/bloc/user_certification_bloc.dart';
import 'package:shopping_group/modle/login/bloc/user_register_bloc.dart';
import 'package:shopping_group/res/colors.dart';
import 'package:shopping_group/res/dimens.dart';
import 'package:shopping_group/utils/object_util.dart';
import 'package:shopping_group/utils/permission_utils.dart';
import 'package:shopping_group/utils/widget_utils.dart';
import 'package:shopping_group/view/button_progress_view.dart';

class UserRegisterPage extends StatefulWidget {
  @override
  _UserRegisterPageState createState() => _UserRegisterPageState();
}

class _UserRegisterPageState extends State<UserRegisterPage> {
  SelectiontEntity _selection = SelectiontEntity();
  WidgetEntity _phoneWidgetEntity = WidgetEntity();
  // WidgetEntity _nameWidgetEntity = WidgetEntity();
  WidgetEntity _passWordWidgetEntity = WidgetEntity();
  WidgetEntity _nextPassWordWidgetEntity = WidgetEntity();
  WidgetEntity _businessPassWordWidgetEntity = WidgetEntity();

  TextEditingController _controllerCode = TextEditingController();
  CountEntity _countEntity = CountEntity();
  UserRegisterBloc _bloc;
  UserCertificationBloc _certificationBloc;
  // MethodChannel _methodChannel;
  bool yqmVie = false;
  // String uid;
  @override
  void initState() {
    super.initState();
    yqmVie =
        ObjectUtil.isEmptyString(BaseConstant.yaoqingrenPhone) ? true : false;
    _selection = SelectiontEntity()..title = '同意《注册服务协议》和《隐私政策》';
    // _nameWidgetEntity = WidgetUtils.initEditText(
    //     '姓名：', '', '请输入姓名', 'name', TextEditingController());
    _phoneWidgetEntity = WidgetUtils.initEditText(
        '手机号码：', '', '请输入手机号码', 'number', TextEditingController());

    _passWordWidgetEntity = WidgetUtils.initEditText(
        '密码：', '', '请输入密码', 'all', TextEditingController());
    _nextPassWordWidgetEntity = WidgetUtils.initEditText(
        '确认密码：', '', '请确认密码', 'all', TextEditingController());
    _businessPassWordWidgetEntity = WidgetUtils.initEditText(
      '邀请码：',
      '',
      '请输入邀请人手机号',
      'number',
      TextEditingController(),
    );
    _bloc = UserRegisterBloc();
    _certificationBloc = UserCertificationBloc();
    //  _onChannel();
  }

  // void _onChannel() {
  //   _methodChannel = MethodChannel(BaseConstant.CHANNEL_METHOD);
  //   PermissionUtils.isStoragePermission(context).then((data) {
  //     if (null != data && data is bool && data) {
  //       _findFile();
  //     } else {
  //       BotToast.showText(text: '请打开sd卡读取权限');
  //     }
  //   });
  //   _findFile();
  // }

  // Future<void> _findFile() async {
  //   return await _methodChannel.invokeMethod('findFile').then((uid) {
  //     setState(() {
  //       yqmVie = true;
  //       if (uid is String && !ObjectUtil.isEmptyString(uid)) {
  //         this.uid = uid;
  //         yqmVie = false;
  //       }
  //     });
  //   });
  // }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: WidgetUtils.showAppar(context, '注册会员'),
      body: GestureDetector(
        onTap: () {
          FocusScope.of(context).requestFocus(FocusNode());
        },
        child: Container(
          height: double.infinity,
          decoration: new BoxDecoration(
            color: Colors.white,
          ),
          child: SingleChildScrollView(
            scrollDirection: Axis.vertical,
            reverse: false,
            padding: EdgeInsets.all(0.0),
            physics: BouncingScrollPhysics(),
            child: _registerBody(),
          ),
        ),
      ),
    );
  }

  Widget _registerBody() {
    return Column(
      children: <Widget>[
        SizedBox(
          height: 16,
        ),
        //  WidgetUtils.showEditText(_nameWidgetEntity),
        WidgetUtils.showEditText(_phoneWidgetEntity),
        // Container(
        //   margin: const EdgeInsets.only(left: 16, right: 16),
        //   child: WidgetUtils.drawCodeDivider(color: Colours.gray_cc),
        // ),
        Row(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            Expanded(
              flex: 1,
              child: Container(
                padding: const EdgeInsets.only(left: 16),
                alignment: FractionalOffset.centerLeft,
                child: WidgetUtils.getTextColorView(
                    '验证码：', Colours.text_2222, Dimens.FONT_SIZE_16),
              ),
            ),
            Expanded(
              flex: 2,
              child: StreamBuilder(
                stream: _certificationBloc.pushDate,
                initialData: _countEntity,
                builder:
                    (BuildContext context, AsyncSnapshot<Object> snapshot) {
                  Object object = snapshot.data;
                  if (object is CountEntity) {
                    _countEntity = object;
                  }
                  return Padding(
                    padding: const EdgeInsets.only(left: 16),
                    child: WidgetUtils.buildTextFieldCode(
                        _controllerCode,
                        TextInputType.phone,
                        '请输入验证码',
                        List<TextInputFormatter>()
                          ..add(LengthLimitingTextInputFormatter(18)),
                        _countEntity.codeCountdownStr,
                        _countEntity.colorStr, codeCallback: (callback) {
                      _usercode();
                    }),
                  );
                },
              ),
            ),
          ],
        ),
        WidgetUtils.drawCodeDivider(height: 1),
        SizedBox(
          height: 8,
        ),
        WidgetUtils.showEditText(_passWordWidgetEntity, isSecrecy: true),
        WidgetUtils.showEditText(_nextPassWordWidgetEntity, isSecrecy: true),
        Offstage(
          offstage: yqmVie,
          child: Column(
            children: <Widget>[
              WidgetUtils.itmeStyleView(
                '邀请码：',
                ObjectUtil.isEmptyString(BaseConstant.yaoqingrenPhone)
                    ? ''
                    : BaseConstant.yaoqingrenPhone
                        .replaceAll(' ', '')
                        .replaceAll('\t', '')
                        .replaceAll('\n', ''),
                textAlign: TextAlign.end,
                bewteenleft: 16,
              ),
              WidgetUtils.drawCodeDivider(height: 1),
            ],
          ),
        ),
        Offstage(
          offstage: !yqmVie,
          child: WidgetUtils.showEditText(_businessPassWordWidgetEntity),
        ),
        //   WidgetUtils.showEditText(_businessPassWordWidgetEntity),
        SizedBox(
          height: 32,
        ),
        _showXyView(_selection),
        SizedBox(
          height: 8,
        ),
        ButtonProgressView.crateCupertinoView('注册', horizontalPadding: 8,
            cupertinoCall: () {
          _userLogin();
        }),
      ],
    );
  }

//校验获取验证码格式
  void _usercode() {
    String phonename = _phoneWidgetEntity.controller.text;
    if (ObjectUtil.isEmptyString(phonename)) {
      BotToast.showText(text: '请输入您的手机号');
      return;
    }
    if (phonename.length != 11) {
      BotToast.showText(text: '请输入正确的手机号');
      return;
    }

    _certificationBloc.verificationDate.add(phonename);
  }

  Widget _showXyView(SelectiontEntity entity) {
    return WidgetUtils.getCheckboxIocnView(entity, blackCall: () {
      setState(() {
        entity.isSelect = !entity.isSelect;
      });
    }, verticalPadding: 0);
  }

  void _userLogin() {
    //   String name = _nameWidgetEntity.controller.text;
    String phonename = _phoneWidgetEntity.controller.text;
    String pwdname = _passWordWidgetEntity.controller.text;
    String pwdNextname = _nextPassWordWidgetEntity.controller.text;
    String businessPwd = !yqmVie
        ? _businessPassWordWidgetEntity.controller.text
        : BaseConstant.yaoqingrenPhone;
    String validateCode = _controllerCode.text;
    // if (ObjectUtil.isEmptyString(name)) {
    //   BotToast.showText(text: '请输入您的姓名');
    //   return;
    // }
    if (ObjectUtil.isEmptyString(phonename)) {
      BotToast.showText(text: '请输入您的手机号');
      return;
    }
    if (phonename.length != 11) {
      BotToast.showText(text: '请输入正确的手机号');
      return;
    }
    if (ObjectUtil.isEmptyString(validateCode)) {
      BotToast.showText(text: '请获取短信验证码');
      return;
    }
    if (ObjectUtil.isEmptyString(pwdname)) {
      BotToast.showText(text: '请输入密码');
      return;
    }
    if (pwdname.length < 6) {
      BotToast.showText(text: '密码至少6位');
      return;
    }
    if (ObjectUtil.isEmptyString(pwdNextname)) {
      BotToast.showText(text: '请再次输入密码');
      return;
    }

    if (pwdNextname.length < 6) {
      BotToast.showText(text: '确认密码至少6位');
      return;
    }
    if (pwdNextname != pwdname) {
      BotToast.showText(text: '两次密码不一致');
      return;
    }

    // if (ObjectUtil.isEmptyString(uid) &&
    //     ObjectUtil.isEmptyString(businessPwd)) {
    //   BotToast.showText(text: '请输入邀请码或邀请人手机号');
    //   return;
    // }

    if (!yqmVie && ObjectUtil.isEmptyString(businessPwd)) {
      BotToast.showText(text: '请输入邀请人手机号');
      return;
    }

    if (!_selection.isSelect) {
      BotToast.showText(text: '请勾选同意协议');
      return;
    }

    Map<String, dynamic> data = {};
    data['phone'] = phonename;
    // data['name'] = name ?? "";
    data['validateCode'] = validateCode;
    data['pwd'] = pwdname;
    data['rePwd'] = pwdNextname;
    data['upCustId'] = businessPwd;
    _bloc.saveDate.add(data);
  }

  @override
  void dispose() {
    _controllerCode.dispose();
    // _nameWidgetEntity.controller.dispose();
    _passWordWidgetEntity.controller.dispose();
    _nextPassWordWidgetEntity.controller.dispose();
    _businessPassWordWidgetEntity.controller.dispose();
    _phoneWidgetEntity.controller.dispose();
    _bloc?.dispose();
    super.dispose();
  }
}
